package com.auroramanito.uaa.rest;

import com.auroramanito.uaa.domain.User;
import com.auroramanito.uaa.service.UserService;
import lombok.Data;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserResource {
    private static UserService userService;


    @GetMapping("/greeting")
    public String greeting(){
        return "Hello World";
    }

    @PostMapping("/greeting")
    public String makeGreeting(@RequestParam String name,@RequestBody Profile profile){
        return "Hello World！POST!" + name + profile.gender;

    }

    @PutMapping("/greeting/{name}")
    public String putGreeting(@PathVariable String name){
        return "Hello World！PUT!" + name;
    }

    /**
     *  GetMapping无法携带requestBody
     * */
    @GetMapping("principal")
    public Authentication getPrincipal(){
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @GetMapping("/users/{username}")
    public String getCurrentUsername(@PathVariable String username){
        return "hello," + username;
    }

    /**
     * 方法权限ADMIN，URL权限是USER
     *
     * 7.2 方法级注解 测试PreAuthorize 和 postAuthorize
     *
     * */
    @PreAuthorize("hasRole('ADMIN')")
//    @PostAuthorize("authentication.name.equals(returnObject.username)")
    @GetMapping("/users/by-email/{email}")
    public User getUserByEmail(@PathVariable String email){
        return userService.findOptionalByEmail(email).orElseThrow();
    }

    /**
     *
     *
     * 7.3 RABC和角色分配权限
     *
     * */
    @GetMapping("/users/manager")
    public String getManagerResource(){
        return "hi";
    }

    @Data
    static class Profile{
        private String gender;
        private String idNo;
    }

}
